package cn.ym.user.service.impl;

import cn.ym.basic.exception.BusinessException;
import cn.ym.basic.util.Md5Utils;
import cn.ym.basic.util.StrUtils;
import cn.ym.org.domain.Employee;
import cn.ym.org.domain.Shop;
import cn.ym.user.domain.Logininfo;
import cn.ym.user.domain.User;
import cn.ym.user.mapper.LogininfoMapper;
import cn.ym.user.mapper.UserMapper;
import cn.ym.user.service.IUserService;
import cn.ym.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.validation.constraints.Email;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private  LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Override
    public void add(User user) {
        //1.处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //2.创建Logininfo对象
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//1-用户
        logininfo.setDisable(true);
        //3.将Logininfo对象添加到数据库，并生成自增id
        logininfoMapper.add(logininfo);//自增长id
        //4.将logininfo_id设置到user对象中
        user.setLogininfoId(logininfo.getId());
        //5.添加到数据库
        super.add(user);
    }

    @Override
    public void delete(Long id) {
        //1.查询user对象
        User user = userMapper.findOne(id);
        //2.删除logininfo信息
        logininfoMapper.delete(user.getLogininfoId());
        //3.删除user信息
        super.delete(id);
    }

    @Override
    public void update(User user) {
        //1.处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //2.查询到原来的user对象
        User oldUser = userMapper.findOne(user.getId());
        user.setLogininfoId(oldUser.getLogininfoId());
        //3.更新数据t_user
        super.update(user);
        //4.更新数据t_logininfo
        Logininfo oldLogininfo = logininfoMapper.findOne(oldUser.getLogininfoId());
        BeanUtils.copyProperties(user,oldLogininfo);
        //5.属性同名原则会把员工的id拷贝给登录信息对象的id
        oldLogininfo.setId(oldUser.getLogininfoId());
        logininfoMapper.update(oldLogininfo);

    }
    /**
     * ：手机号码注册
     * @param
     * @return
     */
    @Override
    public void phoneRegister(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");

        //一：校验 - 空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(password)  || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空");
        }

        //二：校验 - 密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }

        //三：校验 - 手机验证码是否过期，是否正确 [9555:4545455454545]
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj==null){
            throw new BusinessException("手机验证码过期");
        }
        if(!obj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("手机验证码错误");
        }

        //四：添加到数据库，密码加密加盐
        User user = map2User(phone,password);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加t_logininfo
        logininfoMapper.add(logininfo);//添加之后会生成自增长id
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

    }
    /**
     * 接口：邮箱注册
     * @param
     * @return
     */

    @Override
    public void emailRegister(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //一：校验 - 空值校验
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("信息不能为空");
        }
        //二：校验 - 密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        //3.该店铺是否已经被入驻过 - 怎么判断入驻过？店铺名 + 地址
        User byEmail = userMapper.findByEmail(email);
        if(byEmail != null){
            throw new BusinessException("店铺已经入驻，请直接登陆！忘记密码请找回密码");
        }
        //新建一个user对象
        User user=new User();
        //赋值姓名,用邮箱
        user.setUsername(email);
        //赋值邮箱
        user.setEmail(email);
        //获取一个新的盐值
        String salt = StrUtils.getComplexRandomString(32);
        //保存盐值
        user.setSalt(salt);
        //加密密码
        String md5 = Md5Utils.encrypByMd5(password + salt);
        //赋值密码
        user.setPassword(md5);
        //赋值状态-禁用
        user.setState(0);

        //新建一个logininfo对象
        Logininfo logininfo=new Logininfo();
        //使用工具类拷贝
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);
        //1.先添加t_logininfo
        logininfoMapper.add(logininfo);//添加之后会生成自增长id
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        user.setState(1);
        //调用mapper接口添加user对象
        userMapper.add(user);

            /**发送邮件：告诉用户激活邮件使用*/

            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            //发送人
            helper.setFrom("210513347@qq.com");
            helper.setSubject("店铺激活邮件");
            //true - 能够再内容中编写html标签 - 会解析
            helper.setText("<h1>您已成功注册!!!</h1><a href='http://localhost:8080/user/active/"+user.getId()+"'>点击该链接激活</a>",
                    true);
            //收件人
            helper.setTo(user.getEmail());
            javaMailSender.send(mimeMessage);

    }




    //类型转换
    private User map2User(String phone, String password) {
        User user = new User();
        //电话
        user.setUsername(phone);
        user.setPhone(phone);

        //对密码和盐值进行处理
        String salt = StrUtils.getComplexRandomString(32);
        //使用MD5工具类加密密码:加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;

    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //底层会按照属性同名原则进行属性的拷贝：id,username,phone,email,salt,password
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//1表示用户
        logininfo.setDisable(true);
        return logininfo;
    }


}
